package com.shenxuchen.crm.web.controller;

import com.shenxuchen.crm.constant.Constants;
import com.shenxuchen.crm.pojo.User;
import com.shenxuchen.crm.service.UserService;
import com.shenxuchen.crm.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private HttpSession session;

    @Value("${salt}")
    private String salt;

    @PostMapping("save")
    @ResponseBody
    public Map save(User user) {
        user.setId(UUIDUtils.getUUID());
        User loginUser = (User) session.getAttribute(Constants.LOGIN_USER);
        user.setCreateBy(loginUser.getLoginAct() + "|" + loginUser.getName());
        user.setCreateTime(Constants.SDF19.format(new Date()));
        userService.save(user);

        return Constants.RESP.SUC;
    }

    @GetMapping("logout")
    public String logout(HttpServletResponse response) {
        // 移除session中的用户信息
        session.removeAttribute(Constants.LOGIN_USER);

        // 删除cookie中的用户名和密码，否则退出之后又会自动登录
        Cookie cookie = new Cookie(Constants.COOKIE_USERNAME, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");

        Cookie cookie2 = new Cookie(Constants.COOKIE_PASSWORD, null);
        cookie2.setMaxAge(0);
        cookie2.setPath("/");

        response.addCookie(cookie);
        response.addCookie(cookie2);

        return "redirect:/";
    }

    @PutMapping("changePwd")
    @ResponseBody
    public Map changePwd(String oldPwd, String newPwd) {
        User user = (User) session.getAttribute(Constants.LOGIN_USER);
        userService.changePwd(user.getId(), oldPwd, newPwd);

        return new HashMap() {{
           put("success", true);
        }};
    }

    /*
        对于接口的返回值
            查询：返回查询的数据
            其它：返回一个Map
                 success: 是否成功
                 message: 提示消息
     */

    @PostMapping("login")
    @ResponseBody
    public Map login(String username, String password, Boolean rememberMe,
                     HttpServletRequest request, HttpServletResponse response) {
        String userIP = request.getRemoteAddr();
        User user = userService.login(username, password, userIP);

        // 保存登录信息到 session 中，方便获取用户信息，同时还能作为后续判断是否登录的依据。
        session.setAttribute(Constants.LOGIN_USER, user);

        if (rememberMe) {
            int maxAge = 3600 * 24 * 10;
            Cookie cookie = new Cookie(Constants.COOKIE_USERNAME, username);
            cookie.setMaxAge(maxAge);
            cookie.setPath("/");

            password = DigestUtils.md5DigestAsHex((salt + password).getBytes());
            Cookie cookie2 = new Cookie(Constants.COOKIE_PASSWORD, password);
            cookie2.setMaxAge(maxAge);
            cookie2.setPath("/");

            response.addCookie(cookie);
            response.addCookie(cookie2);
        }

        return new HashMap() {{
            put("success", true);
        }};
    }

    @GetMapping("owners")
    @ResponseBody
    public List getOwners() {
        return userService.getOwners();
    }
}
